<template>
  <div class="page-mark-top">
    <div class="header">
      <i class="iconfont icon-help" @click="helpVisible=true" title="帮助文档"></i>
      <Button type="primary" @click="view">预览</Button>
      <Button type="primary" @click="save">保存</Button>
      <Button type="success" @click="setData">定义数据源</Button>
    </div>

    <Modal width="700px" v-model="helpVisible" title="帮助文档" footer-hide class="visual-help-model">
      <p>
        <label for>布局：</label>
        可视化布局是采用了24栅格系统，将区域进行24等分，这样可以轻松应对大部分布局问题。使用栅格系统进行网页布局，可以使页面排版美观、舒适。
      </p>
      <div class="visual-help-footer">
        <Button type="primary" @click="helpVisible=false">确定</Button>
      </div>
    </Modal>

    <Modal
      width="700px"
      v-model="jsonEditVisual"
      title="数据查看/编辑"
      footer-hide
      class="visual-array-edit-model"
    >
      <div id="arrayEditHeader"></div>
      <div class="array-edit-footer">
        <Button @click="cancelHandler" style="margin-right:8px">取消</Button>
        <Button type="primary" @click="okHandler">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { saveTemplate, updateTemplate } from 'http/api/mark'
import { routePathData } from 'assets/scripts/common'
import bus from 'assets/scripts/bus';

export default {
  computed: {
    ...mapState({
      components: state => state.mark.components,
      layout: state => state.mark.layout,
      source: state => state.mark.source
    })
  },
  data () {
    return {
      helpVisible: false,
      jsonEditVisual: false,
      arrayEditor: null,
      componentName: '', // 组件名称
      componentDesc: '', // 组件描述
      componentId: ''
    };
  },
  methods: {
    ...mapActions(['setSource']),

    // 设置编辑的数据
    setHeaderData ({ desc, id, name }) {
      this.componentName = name;
      this.componentDesc = desc;
      this.componentId = id;
    },

    // 设置数据源的数据
    setData () {
      this.jsonEditVisual = true;

      if (!this.arrayEditor) {
        this.arrayEditor = new this.$jsoneditor(
          document.getElementById('arrayEditHeader'),
          {
            search: false,
            mode: 'text',
            indentation: 2
          }
        );
      }

      this.arrayEditor.set(this.source);
    },

    // 确定编辑
    okHandler () {
      try {
        let value = this.arrayEditor.get();
        this.setSource(value);
        this.cancelHandler();
      } catch (err) {
        console.log(err);
        this.$Message.error('请输入正确的数据');
      }
    },

    // 取消编辑
    cancelHandler () {
      this.jsonEditVisual = false;
    },

    // 组件名称 组件描述填写弹框
    setComponentNameInfo (successCallBack) {
      this.$Modal.confirm({
        render: (h) => {
          return h('div', {}, [
            h('span', {
              style: 'margin-bottom:6px;display:inline-block;'
            }, '模板名称'),
            h('Input', {
              props: {
                value: this.componentName,
                autofocus: true,
                placeholder: '请输入模板名称'
              },
              on: {
                input: (val) => {
                  this.componentName = val;
                }
              }
            }),
            h('span', {
              style: 'margin-bottom:6px;display:inline-block;margin-top: 16px;'
            }, '模板描述'),
            h('Input', {
              props: {
                value: this.componentDesc,
                autofocus: true,
                placeholder: '请输入模板描述'
              },
              on: {
                input: (val) => {
                  this.componentDesc = val;
                }
              }
            }),
            h('div', {
              style: 'margin-top: 16px;text-align: right;'
            }, [
              h('Button', {
                style: 'margin-right: 8px;',
                on: {
                  click: () => {
                    this.$Modal.remove();
                  }
                }
              }, '取消'),
              h('Button', {
                props: {
                  type: 'primary'
                },
                on: {
                  click: () => {
                    if (!this.componentName) {
                      return this.$Message.warning('请填写组件名称！');
                    }
                    this.$Modal.remove();
                    successCallBack && successCallBack()
                  }
                }
              }, '确定')
            ])
          ])
        }
      })
      document.getElementsByClassName('ivu-modal-confirm-footer')[0].style.display = 'none'
    },

    // 数据保存
    save () {
      if (this.components && this.components.length === 0) {
        this.$Message.error('没有可保存的组件');
        return false;
      }
      this.setComponentNameInfo(() => {
        let result = {
          config: {
            components: this.components,
            layout: this.layout
          },
          name: this.componentName,
          desc: this.componentDesc
        }
        // 编辑
        if (this.componentId) {
          updateTemplate({ result, id: this.componentId }).then(res => {
            this.componentName = ''
            this.componentDesc = ''
            this.componentId = ''
            this.$Message.success('编辑成功');
            this.$router.push({
              path: routePathData.templateManage
            })
          }).catch(err => {
            this.$Message.error(err)
          })
        } else {
          // 新增
          saveTemplate(result).then(res => {
            this.componentName = ''
            this.componentDesc = ''
            this.$Message.success('保存成功')
            this.$router.push({
              path: routePathData.templateManage
            })
          }).catch(err => {
            this.$Message.error(err)
          })
        }
      })
    },

    // 数据预览
    view () {
      console.log(this.layout)
      console.log(this.components)
      this.$router.push('/home/mark/preview')
    }
  },
  mounted () {
    bus.$on('setHeaderData', this.setHeaderData);
  },
  beforeDestroy () {
    bus.$off('setHeaderData', this.setHeaderData);
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
@import '../../assets/theme/themeBlue.less';
.page-mark-top {
  height: 50px;
  border-bottom: #e6e6e6 1px solid;
  button {
    float: right;
    margin-right: 10px;
  }
  .header {
    overflow: hidden;
    position: relative;
    top: 9px;
  }
  .icon-help {
    float: right;
    font-size: 20px;
    position: relative;
    top: 0px;
    margin-right: 10px;
    cursor: pointer;
    &:hover {
      color: @primary;
    }
  }
}
</style>

<style lang="less">
.visual-help-model {
  p {
    line-height: 26px;
    margin-bottom: 20px;
    label {
      font-weight: bold;
    }
  }
  .ivu-modal-body {
    padding-bottom: 72px;
  }
  .visual-help-footer {
    float: right;
    margin-top: 20px;
  }
}
</style>
